from django.contrib import admin
from .models import Product, Comment, Rate, Tags, User as ProductUser, UserTagPrefer, LikeComment
from django.utils.html import format_html


@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = [
        'id',
        'name',
        'price', 
        'shop_name',
        'shop_type',
        'd_rate_nums',
    ]
    list_display_links = ("id", "name",)
    # 移除list_filter以避免DISTINCT查询
    # list_filter = ('shop_type', 'price')
    list_per_page = 20
    search_fields = ['name', 'shop_name']
    readonly_fields = ('id',)
    
    def get_queryset(self, request):
        """使用前台相同的数据获取方式"""
        # 使用简单的查询，类似前台views.py
        qs = Product.objects.order_by('-price')
        return qs
    
    def get_ordering(self, request):
        """自定义排序，避免复杂查询"""
        return ['-price']


@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
    list_display = ['id', 'user', 'content', 'product', 'create_time']
    # 移除list_filter以避免DISTINCT查询
    # list_filter = ['create_time']
    search_fields = ['content']
    list_per_page = 20
    
    def get_queryset(self, request):
        """使用简单的数据获取方式"""
        return Comment.objects.order_by('-create_time')


@admin.register(Rate)
class RateAdmin(admin.ModelAdmin):
    list_display = ['id', 'user', 'product', 'mark', 'create_time']
    # 移除list_filter以避免DISTINCT查询
    # list_filter = ['mark', 'create_time']
    list_per_page = 20
    
    def get_queryset(self, request):
        """使用简单的数据获取方式"""
        return Rate.objects.order_by('-create_time')


@admin.register(Tags) 
class TagsAdmin(admin.ModelAdmin):
    list_display = ['id', 'name']
    search_fields = ['name']
    
    def get_queryset(self, request):
        """使用简单的数据获取方式"""
        return Tags.objects.order_by('name')


@admin.register(ProductUser)
class ProductUserAdmin(admin.ModelAdmin):
    list_display = ['id', 'username', 'email', 'created_time']
    search_fields = ['username', 'email']
    list_per_page = 20
    
    def get_queryset(self, request):
        """使用简单的数据获取方式"""
        return ProductUser.objects.order_by('-created_time')


@admin.register(UserTagPrefer)
class UserTagPreferAdmin(admin.ModelAdmin):
    list_display = ['id', 'user', 'tag', 'score']
    # 移除list_filter以避免DISTINCT查询
    # list_filter = ['score']
    
    def get_queryset(self, request):
        """使用简单的数据获取方式"""
        return UserTagPrefer.objects.order_by('-score')


@admin.register(LikeComment)
class LikeCommentAdmin(admin.ModelAdmin):
    list_display = ['id', 'user', 'comment']
    
    def get_queryset(self, request):
        """使用简单的数据获取方式"""
        return LikeComment.objects.order_by('-id')